var lei = 5;
var leiArray = [];
var iArray = [
    [1,3,4],
    [-1,1,2,3,4],
    [-1,2,3],
    [-5,-4,-1,2,3],
    [-5,-4,-1],
    [-5,-4,-3,-1,1],
    [-4,-3,1],
    [-4,-3,1,3,4],
    [-5,-4,-3,-1,1,2,3,4]
];


var item = document.getElementsByClassName('item');

for(let i=0; i<item.length;i++) {
    (function(i){
        item[i].addEventListener('click',function(){
            console.log(this,i);
            if(leiArray.indexOf(i) != -1) {
                this.style.background = 'red';
                setTimeout(()=>{
                    alert('游戏结束！');
                    rePlay();
                },200)
            }else{
                this.style.background = 'green';
                let iArray_;
                let leiNum = 0;
                if(i < 0 &&  i > 3) {
                    iArray_ = iArray[1];
                }else if(i > 4 && i % 4 == 3) {
                    iArray_ = iArray[3];
                }else if(i > item.length -1 && i < item.length - 4) {
                    iArray_ = iArray[5];
                }else if(i % 4 == 0) {
                    iArray_ = iArray[7];
                }else if(i == 0) {
                    iArray_ = iArray[0];
                }else if(i == 4) {
                    iArray_ = iArray[2];
                }else if( i == item.length -1 ) {
                    iArray_ = iArray[4];
                }else if(i == item.length - 4) {
                    iArray_ = iArray[6];
                }else{
                    iArray_ = iArray[8];
                }
                for(let j=0;j<iArray_.length;j++) {
                    let leiIndex = i + iArray_[j];
                    console.log(leiIndex,leiArray)
                    if(leiArray.indexOf(leiIndex) != -1) {
                        leiNum++;
                    }
                }
                this.innerHTML = leiNum;
            }
        })
    })(i)
}


function rePlay () {
    leiArray = [];
    for(let i = 0; i<lei;i++) {
        let index = parseInt(Math.random()*16,10);
        if(leiArray.indexOf(index) != -1) {
            i--;
        }else{
            leiArray.push(index);
        }
    }
    for(let i=0; i<item.length;i++) {
        item[i].style.background = '#555';
        item[i].innerHTML = '';
    }
}
rePlay();